/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package service;

import java.io.IOException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.PathParam;
import javax.ws.rs.Consumes;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.Produces;

import com.google.gson.Gson;
import common.RandomFilename;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Iterator;
import javax.imageio.ImageIO;
import javax.ws.rs.POST;
import service.db.DatabaseOperations;

import common.*;
import java.awt.geom.AffineTransform;
import javax.imageio.*;
import javax.imageio.stream.FileImageOutputStream;


/**
 * REST Web Service
 *
 * @author frke0900
 */

@Path("image")
public class ImageResource {
    @Context
    private UriInfo context;
    private String savePath = "/home/datateknik/www/imageshare/";
    private String saveThumbPath = "/home/datateknik/www/imageshare/thumbnail/";
    public static String imageBaseUrl = "http://datateknik.titandreams.se/";
    public static String thumbnailBaseUrl = "http://datateknik.titandreams.se/thumbs/";
    
    private ImageOpeations imageOperation;

    /** Creates a new instance of ImageResource */
    public ImageResource() {
        imageOperation = new ImageOpeations();
    }

    /**
     * Retrieves representation of an instance of service.ImageResource
     * @return an instance of java.lang.String
     */
    @GET
    @Produces("application/json")
    @Path("/{lat}/{lng}")
    public String getJson(@PathParam("lat") double lat, @PathParam("lng") double lng) {
        
        System.out.println("Get connection accepted!");
        
        String returnData;
        try {
            System.out.println("LAT: "+lat+", LONG: "+lng);
            returnData = DatabaseOperations.getImages(lat, lng);
        } 
        catch(Exception ex) {
            ex.printStackTrace();
            returnData = "{'status':'Error', 'message':'"+ex+"'}";
        }
        
        return returnData;
    }

    /**
     * Post method for updating or creating an instance of ImageResource
     * 
     * firstly a ImageJsonObject is created by the incomming json message
     * then saves the image to disk (thumb and full)
     * then adds the new photo to database
     * 
     * @param content representation for the resource
     * @return Json string with status ok if everything worked, else a json string with status error and a message
     */
    @POST
    @Consumes("application/octet-stream")
    public String postJson(byte[] c) {
        System.out.println("Post connection accepted");
        String returnData = null;

        String content = new String(c);
        //System.out.println(content);
        try {
            Gson g = new Gson();
            ImageJsonObject ijo = g.fromJson(content, ImageJsonObject.class);

            saveImgToDisk(ijo);                 //save image and set ijo.image to the path
            DatabaseOperations.saveNewImage(ijo);

            returnData = "{'status':'OK', 'message':'image uploaded'}";
        } catch(Exception ex) {
            ex.printStackTrace();
            returnData = "{'status':'Error', 'message':'"+ex+"'}";
        }

        return returnData;
    }
    
    @GET
    @Produces("application/json")
    @Path("/{id: \\d++}/comments")
    public String getComment(@PathParam("id") int id) {
        System.out.println("Get comments connection accepted!");
        
        String returnData;
        try {
            returnData = DatabaseOperations.getComments(id);
        } 
        catch(Exception ex) {
            ex.printStackTrace();
            returnData = "{'status':'Error', 'message':'"+ex+"'}";
        }
        
        return returnData;
    }
    
    @POST
    @Consumes("application/json")
    @Path("/{id: \\d++}/comments")
    public String postComment(String content, @PathParam("id") int id) {
        System.out.println("get comment connection accepted");
        String returnData = null;
        
        try {
            Gson g = new Gson();
            CommentObject co = g.fromJson(content, CommentObject.class);
            DatabaseOperations.newComment(co, id);
            returnData = "{'status':'OK', 'message':'comment saved'}";
        }
        catch(Exception ex) {
            ex.printStackTrace();
            returnData = "{'status':'Error', 'message':'"+ex+"'}";
        }
        
        return returnData;
    }

    /**
     * Save the full image and a thumbnail to disk, changes ijo.img to the filename of the newly saved file
     * 
     * @param ijo
     * @throws CustomException 
     */
    private void saveImgToDisk(ImageJsonObject ijo) throws CustomException {
        String returnData = null;

        try {      
            Image image = imageOperation.base64ToImage(ijo.getImg(), ijo.getExtention());
            File imageFile = imageOperation.saveImage(image, savePath);

            ijo.setImg(imageFile.getName());          //save filepath to use when saving to database
            System.out.println(ijo.toString());
            
            imageOperation.saveThumbnail(savePath, ijo.getImg());

        } 
        catch(Exception ex) {
            //ex.printStackTrace();
            //throw new CustomException(ex.getMessage());
            System.out.println("saveImageToDisk MAIN "+ex.getMessage());
        }
    }
}
